<?php

class M_student_attendance Extends MY_Model
{

	public function generatestudentattendance($e_id)
	{
		$e = $this->db->select('e_id')
				 ->where('e_id',$e_id)
				 ->where('ay_id',$this->c_sy->id)
				 ->limit(1)->get('student_attendance');
		if($e->num_rows() >= 1)
		{
			$this->generate_attendance_detailed($e_id);
			return TRUE;
		}else{
			$this->db->insert('student_attendance', ['e_id' => $e_id,'ay_id'=>$this->c_sy->id]);
			if($this->db->affected_rows() >=1 )
			{
				$this->generate_attendance_detailed($e_id);
				return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
			}else{
				return FALSE;
			}
		}
	}


	public function generate_attendance_detailed($e_id = '')
	{
		$CI =& get_instance();
		$CI->load->model('M_gperiods','mgep');

		$check = 'SELECT e_id from student_attendance_detailed WHERE e_id = ? AND ay_id = ? LIMIT 1';
		$_check = $this->db->query($check,[$e_id,$this->c_sy->id]);

		if($_check->num_rows() >= 1)
		{
			return TRUE;
		}else
		{
			$gperiods = $CI->mgep->get_gperiods();
			
			if($gperiods)
			{
				foreach ($gperiods as $key => $value) {
					$insert[$key]['e_id'] = $e_id;
					$insert[$key]['gperiod'] = $value->gp_id;
					$insert[$key]['ay_id'] = $this->c_sy->id;
					$insert[$key]['created'] = NOW;
				}

				$this->db->insert_batch('student_attendance_detailed',$insert);
				return $this->db->affected_rows() >=1 ? TRUE : FALSE;
			}else{
				return FALSE;
			}
		}
	}

	public function generate_attendance_by_gp($e_id = '', $gp_id = false)
	{
		$CI =& get_instance();
		$CI->load->model('M_gperiods','mgep');

		$check = 'SELECT e_id from student_attendance_detailed WHERE e_id = ? AND gperiod = ? LIMIT 1';
		$_check = $this->db->query($check,[$e_id,$gp_id]);
		
		if($_check->num_rows() >= 1)
		{
			return TRUE;
		}else
		{
			$gperiods = $CI->mgep->get_gperiods($gp_id);
			
			if($gperiods)
			{
				foreach ($gperiods as $key => $value) {
					$insert[$key]['e_id'] = $e_id;
					$insert[$key]['gperiod'] = $value->gp_id;
					$insert[$key]['ay_id'] = $this->c_sy->id;
					$insert[$key]['created'] = NOW;
				}

				$this->db->insert_batch('student_attendance_detailed',$insert);
				return $this->db->affected_rows() >=1 ? TRUE : FALSE;
			}else{
				return FALSE;
			}
		}
	}

	public function set_student_attendance($db_column,$primary_key,$data)
	{
		$this->db->set($db_column,$data['option'])
					->where('id',$primary_key)
					->update('student_attendance_detailed');
		return $this->db->affected_rows() >=1 ? TRUE : FALSE;
	}
}